Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to use the same table twice in a select query?

Tags:

sql

Hi I have the following query, and I'm wondering what it means:

SELECT c1.id as sender, c2.id as replier
   FROM contacts c1, contacts c2;

How can you use the same table twice?

like image 469
locoboy Avatar asked Sep 12 '11 05:09

locoboy


People also ask

Can I use with twice in SQL?

No. CTEs can only be used on a single operation.

Can we use join on same table?

The self-join is a special kind of joins that allow you to join a table to itself using either LEFT JOIN or INNER JOIN clause. You use self-join to create a result set that joins the rows with the other rows within the same table.

How do I join two columns from the same table in SQL?

The following example shows how to concatenate three different columns: (SELECT id, email1 AS email FROM customer) UNION (SELECT id, email2 AS email FROM customer) UNION (SELECT id, email3 AS email FROM customer) ORDER BY id, email; As you can see, it's important that all the queries return the same columns.


2 Answers

This query creates a table containing all possible pairs of contact ids.

For example, if your contact ids were 1, 2, and 3 you would get, as a result

1 1
1 2
1 3
2 1
2 2
2 3
3 1
3 2
3 3
like image 134
Ray Toal Avatar answered Oct 22 '22 07:10

Ray Toal


Yes, you can use the same table more than once within the same SELECT query.

Note that you only need to use table correlation names (colloquially 'aliases') when the table appears more than once within the same scope. For example, the following SELECT query uses the same table twice but, because each is within a distinct scope (each separated by the UNION keyword), no table correlation name is required:

SELECT id, 'Sender' AS contact_narrative
  FROM contacts
 WHERE something = 1
UNION
SELECT id, 'Replier' AS contact_narrative
  FROM contacts
 WHERE something = 2;
like image 43
onedaywhen Avatar answered Oct 22 '22 09:10

onedaywhen