简体   繁体   中英

How to get unique data from two tables using mysql?

I have two tables one table has details of projects thats are unique and another table has image of this project but multiple.

I want one image with one project.

Structure of data :

Table 1:

Project_id  Project_Name 
291          Demo1
292          Demo2

Table 2:

Project_id   Img_name   Attr_id
291          p1.png     11
291          p2.png     12

I want to get image where attr_id is 11

So output will be

project_id    Project_name     Img_name    Attr_id
291           Demo1            p1.png       11

So How to do this ?

In your case you can use the JOIN -function of mysql:

SELECT a.Project_id, a.Project_Name, b.Img_name, b.Attr_id
FROM table2 b INNER JOIN Table1 a ON ( b.Project_id = a.Project_id)
WHERE b.Attr_id = 11

Or you could just filter your Selection by a WHERE ... AND -Construction:

select * from table1 a,table2 b where a.project_id = b.project_id and attr_id=11

Both ways will result in the same output:

291  Demo1  p1.png  11

you can have a join on these two tables for getting the result :

"select t1.project_id,t1.project_name,t2.img_name,t2.attr_id
from table1 t1,table2 t2
where t1.project_id=t2.project_id
and t2.attr_id=11";

If you don't want to specifically query the Attr_id try this one. Should get you the image with the lowest Attr_id related to the project

SELECT table1.project_id, table1.project_name, image.Img_name, image.Attr_id  
FROM table1 
    INNER JOIN (SELECT * FROM table2 ORDER BY Attr_id ASC LIMIT 1) 
        AS image ON table1.project_id = image.project_id 
WHERE table1.project_id = 291

使用mysql JOIN

select a.Project_id,a.Project_Name,b.Img_name,b.Attr_id   from table1 a join table2 b  ON a.project_id = b.project_id where b.attr_id=11

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM