简体   繁体   English

如何使用mysql从两个表中获取唯一数据?

[英]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 我想得到attr_id为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: 在你的情况下你可以使用mysql的JOIN函数:

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: 或者您可以通过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 : 你可以有一个join这两个表用于获取结果:

"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. 如果您不想专门查询Attr_id,请尝试使用此方法。 Should get you the image with the lowest Attr_id related to the project 应该为您提供与项目相关的最低Attr_id的图像

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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