Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

basic sql : selecting the same column multiple times in one query, when each occurrence is dependent on different where clause

Tags:

sql

What is the best way to to perform this query. I have the following table

mytable with columns

x y 
1 a
2 b
3 c

and I would like to (in pseudo sql)

select x as x1 ,x as x2, x as x3 from mytable where ????

when

x1 is x where y=a

x2 is x where y=b

x3 is x where y=c

so I would like as a result

1, 2, 3

I am currently using cte's and and a very large dataset, I am trying to reduce the query time, is it always necessary to have 3 table scans ?

like image 353
NimChimpsky Avatar asked Nov 04 '10 13:11

NimChimpsky


People also ask

How do I SELECT multiple values from the same column in SQL?

Note – Use of IN for matching multiple values i.e. TOYOTA and HONDA in the same column i.e. COMPANY. Syntax: SELECT * FROM TABLE_NAME WHERE COLUMN_NAME IN (MATCHING_VALUE1,MATCHING_VALUE2);

Which operator is used to fetch data when any one of the multiple conditions is true?

The SQL AND & OR operators are used to combine multiple conditions to narrow data in an SQL statement. These two operators are called as the conjunctive operators.

How can use two conditions in SQL query?

You can specify multiple conditions in a single WHERE clause to, say, retrieve rows based on the values in multiple columns. You can use the AND and OR operators to combine two or more conditions into a compound condition. AND, OR, and a third operator, NOT, are logical operators.


2 Answers

You should use 3 queries. It will be a lot faster with proper indexing when self joins. Additionally it will be more readable.

If you would like one query call, it might be this :)

SELECT
(SELECT x FROM table WHERE y=1) AS x1,
(SELECT x FROM table WHERE y=2) AS x2,
(SELECT x FROM table WHERE y=3) AS x3
like image 51
Silver Light Avatar answered Oct 03 '22 18:10

Silver Light


I would of done this :

SELECT
    tableRowA.x as x1
    tableRowB.x as x2
    tableRowC.x as x3
FROM
    table as tableRowA,
    table as tableRowB,
    table as tableRowC
WHERE
    tableRowA.y = 1
    tableRowB.y = 2
    tableRowC.y = 3

Bit easier to understand, and pull out more info if you need multiple columns from each row

like image 20
aqm Avatar answered Oct 03 '22 19:10

aqm