加入两个表,其中第二个表需要多次连接

时间:2016-04-11 14:38:26

标签: mysql sql sqlite

嗨,请看我的两张表和数据

 /* wp_posts */

 ID    post_title         post_type   post_status
 1     testproduct        product     publish

 /* wp_postmeta */

 meta_id   post_id   meta_key        meta_value
 1           1       _price           20
 2           1       _regularprice    30
 3           1       _stock_status    instock
 4           1        _qty             3

我需要从这两个表中获取所有数据,以获取产品的每个细节。为此,我写下面的查询,但它不起作用,请帮助。

SELECT p.post_title,m.meta_key,m.meta_value FROM wp_posts p LEFT  JOIN wp_postmeta m LEFT JOIN wp_post_meta m1 ON p.ID = m.post_id AND m.meta_key = '_price' AND m1.meta_key= '_regular_price' WHERE p.post_status = 'publish' AND p.post_type = 'product'

1 个答案:

答案 0 :(得分:1)

看起来你写的查询太复杂了。尽量简化。喜欢这个

select p.post_title,m.meta_key,m.meta_value 
from wp_post p 
join wp_postmeta m on p.id=m.post_id 
where p.post_status = 'publish' AND p.post_type = 'product' and
(m.meta_key='_price' or m.meta_key='_regular_price')