mysql - 更清晰的 SQL 查询

标签 mysql sql

我有 2 个使用外键连接的表,例如:budget_items 表列“id”和交易表列“parent_id”

每个表都有一些相似的列名,例如名称和日期。因此,当我查询表时,我将按如下方式提取数据:

SELECT
                        budget_items.id AS BI_id,
                        budget_items.owner_id as BI_owner,
                        budget_items.name AS BI_name, 
                        budget_items.date AS BI_date,
                        budget_items.amount AS BI_amount,
                        budget_items.type AS BI_type,
                        transactions.id as TRANS_id, 
                        transactions.parent_id as TRANS_parent,
                        transactions.owner_id as TRANS_owner,
                        transactions.amount as TRANS_amount,
                        transactions.date as TRANS_date,
                        transactions.type as TRANS_type,
                        transactions.processed as TRANS_processed,
                        transactions.name AS TRANS_name 
                    FROM
                        myezbudget.budget_items budget_items,
                        myezbudget.transactions transactions
                    WHERE
                        budget_items.id = transactions.parent_id AND
                        budget_items.owner_id = ?`, [req.user.id]

我的问题是,有没有更好的方法来使用更简洁的查询来做到这一点?我尝试了几种不同类型的连接语句,但无法按照我喜欢的方式输出。我绝不是 SQL 专家,如果有任何建议或指导,我将不胜感激。

最佳答案

我会:

  • 使用现代 JOIN 语法。
  • 使用较短的表别名。

查询应该如下所示:

SELECT
    i.id AS BI_id,
    i.owner_id as BI_owner,
    i.name AS BI_name, 
    i.date AS BI_date,
    i.amount AS BI_amount,
    i.type AS BI_type,
    t.id as TRANS_id, 
    t.parent_id as TRANS_parent,
    t.owner_id as TRANS_owner,
    t.amount as TRANS_amount,
    t.date as TRANS_date,
    t.type as TRANS_type,
    t.processed as TRANS_processed,
    t.name AS TRANS_name 
FROM myezbudget.budget_items i
JOIN myezbudget.transactions t on i.id = t.parent_id 
WHERE i.owner_id = ?

关于mysql - 更清晰的 SQL 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53616913/

相关文章:

mysql - 过程的 CALL 不断加载,占用高 CPU,并失败

Python MySQL Update 需要 10-12 秒更新约 1000 条记录

php - 两个 SELECT 语句合并为一个 SQL

mysql - 服务器时区在数据之前的sql查询

php - 将 PDO 结果传递到另一个临时表或插入到临时表

c# - DbLinq 的对象跟踪的性能可以提高吗?

php - 为什么我的 PHP if 语句不能正常工作?

sql - 在DateTime字段中的两个日期之间进行选择-SQL Server

mysql - 如何编写查询来选择值而不再次重复相同的值?

mysql - 在 mysql 5.0.77 中定义触发器的语法错误