SQL - 如何从union表中获取第一个和最后一个记录?

时间:2016-12-17 04:11:25

标签: php sql

SELECT * FROM (
SELECT id_product, picture_url, product_name, product_price, tracking_link, '$ecommerce2->nama_ecommerce' AS table_identity FROM table1 WHERE product_name LIKE '%$search%'
                    UNION
SELECT id_product, picture_url, product_name, product_price, tracking_link, '$ecommerce2->nama_ecommerce' AS table_identity FROM table2 WHERE product_name LIKE '%$search%'
            ) AS big_table ORDER BY big_table.product_price DESC
            LIMIT 1

如何从上面的sql获取第一个和最后一个记录?

3 个答案:

答案 0 :(得分:0)

只需在desc(最后一条记录)和asc之间切换(第一条记录) 和limit 1只有一个记录。

答案 1 :(得分:0)

假设您的联盟因某种原因而重复:

GridView

答案 2 :(得分:0)

(SELECT * FROM (
   SELECT id_product, picture_url, product_name, product_price, tracking_link, '$ecommerce2->nama_ecommerce' AS table_identity FROM table1 WHERE product_name LIKE '%$search%'
                    UNION ALL
   SELECT id_product, picture_url, product_name, product_price, tracking_link, '$ecommerce2->nama_ecommerce' AS table_identity FROM table2 WHERE product_name LIKE '%$search%'
 ) AS big_table1 ORDER BY product_price LIMIT 1)

UNION

(SELECT * FROM (
    SELECT id_product, picture_url, product_name, product_price, tracking_link, '$ecommerce2->nama_ecommerce' AS table_identity FROM table1 WHERE product_name LIKE '%$search%'
                        UNION ALL
    SELECT id_product, picture_url, product_name, product_price, tracking_link, '$ecommerce2->nama_ecommerce' AS table_identity FROM table2 WHERE product_name LIKE '%$search%'
 ) AS big_table2 ORDER BY product_price DESC LIMIT 1)