SQL检索数据很重要

时间:2015-07-20 03:56:00

标签: php mysql codeigniter

$sql = "SELECT distinct `customer_id` FROM( SELECT * FROM `booking` WHERE `confirmed` = 1 ORDER BY `reserve_date` DESC ) as inv";
$query = $this->db->query($sql);

在cms的codeigniter文件的模型php中完美运行

在名为“customer”的表中有一个名为“name”的列 想要在data(customer_id)中按名称“customer”的字段“name”命名$query,并将其存储在$result中 然后,使用$result

做我喜欢的事情

怎么做 - 请帮助我 - 我是codeigniter和php的新手。非常感谢。

2 个答案:

答案 0 :(得分:1)

加入客户表并按名称排序。

SELECT DISTINCT
    customer_id
FROM
    (SELECT 
        *
    FROM
        booking
    WHERE
        confirmed = 1
    ORDER BY reserve_date DESC) AS inv
        INNER JOIN
    customer AS cu ON cu.id = inv.customer_id
ORDER BY cu.name

如果您从未使用LIMIT来预订"预订"您可以通过替换

来优化它
ORDER BY reserve_date DESC 

ORDER BY null

然后你甚至可以重写你的查询成为

SELECT DISTINCT
    inv.customer_id
FROM
    booking AS inv
        INNER JOIN
    customer AS cu ON cu.id = inv.customer_id
WHERE
    inv.confirmed = 1
ORDER BY cu.name;

不要忘记在id, customer_id, confirmed and name列上构建必要的索引。

答案 1 :(得分:0)

$ sql = SELECT DISTINCT booking.customer_id 从预订 INNER JOIN客户在booking.customer_id = customer.customer_id WHERE confirmed = 1 ORDER BY customer.name