在此sql Fifddle示例中的何处执行“ a”。性格不断来自何方?它根本不在桌子上

时间:2019-03-01 01:44:52

标签: mysql

CREATE TABLE IF NOT EXISTS `docs` (
  `id` int(6) unsigned NOT NULL,
  `rev` int(3) unsigned NOT NULL,
  `content` varchar(200) NOT NULL,
  PRIMARY KEY (`id`,`rev`)
) DEFAULT CHARSET=utf8;
INSERT INTO `docs` (`id`, `rev`, `content`) VALUES
  ('1', '1', 'The earth is flat'),
  ('2', '1', 'One hundred angels can dance on the head of a pin'),
  ('1', '2', 'The earth is flat and rests on a bull\'s horn'),
  ('1', '3', 'The earth is like a ball.');

/////////////////////////////////////////////////////////

然后执行实际查询:

SELECT a.id, a.rev, a.content
FROM `docs` a
INNER JOIN (
    SELECT id, MAX(rev) rev
    FROM `docs`
    GROUP BY id
) b ON a.id = b.id AND a.rev = b.rev;


SELECT a.*
FROM `docs` a
LEFT OUTER JOIN `docs` b
    ON a.id = b.id AND a.rev < b.rev
WHERE b.id IS NULL;

a是占位符吗?
人们会去哪里找到对此英语的解释?
我希望有人能引导我们完成这项工作并使之易于理解。 谢谢!

1 个答案:

答案 0 :(得分:0)

“ a”是表格别名

SELECT a.id, a.rev, a.content
FROM `docs` a    # HERE, on this line, the table is given an alias of a
INNER JOIN (
    SELECT id, MAX(rev) rev
    FROM `docs`
    GROUP BY id
) b ON a.id = b.id AND a.rev = b.rev;

该别名是在from子句中的表名之后立即声明的(如上所述)。

别名用于缩写和/或阐明查询。在很多地方都可以声明别名,例如

// verify binding
    if ($ldap_bind) {
    echo "
<head>
<link - stylesheet \link>
</head>
<form class=\"form-horizontal\" action\"form.php\" method=\"POST\" enctype=\"multipart/form-data\">
<fieldset>
<body>
html code....lots of div boxes
<script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"></script>
<script>
$(document).ready(function(){
Various Jquery functions that hide/unhide div boxes
});
</script>
</body>
</fieldset>
</form>
";

            } else {
                echo "<p class='text-error'>Unable to log you in:</p>";

请注意,在大多数数据库中,上面看到的“ as”是可选的,Oracle在声明表或子查询别名时不允许使用“ as”。

自我加入

将表联接到表别名时表别名是至关重要的

#table alias
from tablex as x

#derived table (subquery) alias
select d.* from (select * from t where col1 = 'xyz') as d

#column alias
select col1 as xyz
from tablex as x

没有查询的别名t1和t2根本无法工作。


编辑

很遗憾,我们经常看到别名,其中别名是在查询中“按顺序”定义的。在您的示例中,第一个是“ a”,第二个是“ b”,依此类推。

那是不好的做法。使用别名的一种更有意义的方法是使用表名称中每个单词的“首字母”或为子查询分配一些含义。

在示例中,我建议使用“ d”(对于docs)和“ mr”(对于max(rev))

select
     t1.id as t1_id
   , t2.id as t2_id
from tablex as t1
inner join tablex as t2 on t1.fk = t2.id