mySQL:从ID关联的两个表中获取数据

时间:2014-05-14 15:36:12

标签: mysql

我需要你的帮助。我有两个表:具有下一个结构和数据的产品和演示文稿:

products:
id | name | description | price
5  | iPad | description | 950.00   

presentations:
id_product | name  | price
5          | White | 955.00
5          | Black | 945.00

我需要从'产品'表中获取ID产品,并从'presentation'表中获取与其相关的所有记录。我希望下一个结果在html表或divs:

Product name: Ipad
Description: This is the description based on the text contained if the field of the table

Please, select the ipad you want:        
  (*) Normal - price:  $950.00
  ( ) White  - price:  $955.00
  ( ) Black  - price:  $945.00

我该怎么办?谢谢大家!

4 个答案:

答案 0 :(得分:4)

SELECT 'Normal' AS name, price from products
  WHERE id = 5
UNION
SELECT name, price FROM presentations
  WHERE id_product = 5

答案 1 :(得分:0)

使用请求

select name from products where id=5 and  id in(select id_product from presentations);

select name from products P, presentations Pr whre P.id=Pr.id_product and P.id=5;

答案 2 :(得分:0)

使用INNER JOIN,

SELECT p.name,p.description,p.price,pr.name  AS presentationName,pr.price AS 
presentationPrice
FROM product p INNER JOIN presentations pr ON p.id=pr.id_product WHERE p.id='5'

答案 3 :(得分:0)

如果我不理解你错了,我认为你需要的是两个表之间的联接。像

这样的东西
SELECT prod.name AS product_name, description, pres.name AS presentation_name, pres.price AS price 
FROM products AS prod INNER JOIN presentations AS pres 
ON (prod.id = pres.id_product)`

将返回如下结果:

| product_name |描述| presentation_name |价格|

| iPad |描述|白色| 955.00 |

等等。那是你想要的吗?