Skip to content
Advertisement

How can I use a SQL query result as a column in another query?

I got a view that returns weekday. The result will be a column in WHERE clause, something like this:

 SELECT * FROM dvtv_delivery WHERE (SELECT day FROM dvtv_weekday) = 'Y'

For example:

Today is sunday, in dvtv_weekday returns SUN In dvtv_delivery exist the column SUN

Is it possible in Mysql? When I run nothing appears

Using I use down below, works

  SELECT * FROM dvtv_delivery WHERE SUN = 'Y'

Any answer would really be helpful! Sorry my bad English

Advertisement

Answer

This query:

SELECT day FROM dvtv_weekday

returns a string like 'SUN' and not the name of the column SUN.
So WHERE is equivalent to:

WHERE 'SUN' = 'Y'

which will always return no rows.
You need something like this:

SELECT * FROM dvtv_delivery 
WHERE 
  CASE (SELECT day FROM dvtv_weekday) 
    WHEN 'SUN' THEN SUN
    WHEN 'MON' THEN MON
    WHEN 'TUE' THEN TUE
    WHEN 'WED' THEN WED
    WHEN 'THU' THEN THU
    WHEN 'FRI' THEN FRI
    WHEN 'SAT' THEN SAT
  END = 'Y'

I assume that the table dvtv_delivery has all these columns: SUN, MON, ....

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement