How do you think I should write a query?(MySQL)

时间:2015-06-26 09:41:39

标签: mysql sql

I am trying to write a query to fetch data from three tables but I know how write the query exactly.

I am trying to merge three tables. In the first table it has id and data_name, second table data_id, option_id and property and third table user_id, data_id.

for example:

first table
id -- data_name
1 - veri1
2 - veri2
3 - veri3

second table 
data_id-- property -- option_id 
1 ---------- blue ---- 1
1 ---------- cold ---- 2
2 ---------- gray ---- 1
2 ---------- hot  ---- 2
3 ---------- green---- 1
3 ---------- cold ---- 1

third table
user_id ---  data_id
   1  -------  2
   2  -------  3
   3  -------  1 

This should be the output.

user: 1
data: veri2
properties: gray - hot

What should be the SQL query?

3 个答案:

答案 0 :(得分:0)

I think these SQL will helpful to you.

    select table_1.id, table_2.property, table_3.user_id as user 
    from firsttable as table_1 secondtable as table_2, 
    thirdtable as  table_3 where table_3.user_id= table_2.data_id 
    and table_3.user_id= table_1.id and table_3.user_id =1

Thank you.

答案 1 :(得分:0)

Try this query

    select a.id,a.data_name,c.property from first_table a
    join third_table b on b.user_id=a.id
    join second_table c on c.data_id=b.data_id
   where a.id=1

答案 2 :(得分:0)

This one should do exactly what you requested

select
third.user_id user,
first.data_name data,
group_concat(second.property separator ' - ')
from
third_table third left join (first_table first, second_table second)
on third.data_id = first.id
and second.data_id = first.id
group by third.user_id

group_concat and group by cooperate to get the list of properties per user.