我有几个查询我想合并到1个查询中,我不确定正确的加入是什么。
此查询获取与pid匹配的所有弧:
var arcs = db.Query("SELECT arc FROM comics WHERE `publisher`=" + pid + " GROUP BY arc").ToList();
此查询从arcs表中获取弧的标题:
var ar = db.QuerySingle("SELECT title FROM arcs WHERE id=" + arc.arc);
此查询用于获取与arc.arc和pid匹配的总问题:
var issues = db.Query("SELECT id FROM comics WHERE arc=" + arc.arc + " AND publisher=" + pid);
整个代码:
@{
var pid = Request["pid"];
var db = Database.Open("quickly");
var publisher = db.QuerySingle("SELECT * FROM publishers WHERE id=@0", pid);
Page.Title = publisher.name + " @";
var arcs = db.Query("SELECT arc FROM comics WHERE `publisher`=" + pid + " GROUP BY arc").ToList();
}
<div class="post">
<div class="post-bgtop">
<div class="post-bgbtm">
<h2 class="title">@publisher.name</h2>
<div class="entry">
<p>
<table width="100%" border="0">
<thead>
<tr>
<th align="left">Title</th>
<th>Issues</th>
</tr>
</thead>
<tbody>
@foreach (var arc in arcs) {
var ar = db.QuerySingle("SELECT title FROM arcs WHERE id=" + arc.arc);
var issues = db.Query("SELECT id FROM comics WHERE arc=" + arc.arc + " AND publisher=" + pid);
<tr>
<td><a href="@Href("~/Comics/Arcs?aid=" + arc.arc)">@ar.title</a></td>
<td align="center">@issues.Count</td>
</tr>
}
</tbody>
</table>
</p>
</div>
</div>
</div>
</div>
表格结构:
CREATE TABLE IF NOT EXISTS `arcs` (
`id` int(255) NOT NULL AUTO_INCREMENT,
`title` varchar(255) NOT NULL,
`plot` longtext NOT NULL,
`added` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
UNIQUE KEY `title` (`title`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
CREATE TABLE IF NOT EXISTS `comics` (
`id` varchar(255) NOT NULL,
`arc` int(255) NOT NULL,
`title` varchar(255) NOT NULL,
`issue` decimal(5,1) DEFAULT NULL,
`price` decimal(10,2) NOT NULL,
`plot` longtext NOT NULL,
`publisher` int(255) NOT NULL,
`isbn` varchar(255) NOT NULL,
`published` date NOT NULL,
`cover` varchar(255) NOT NULL DEFAULT './images/nopic.jpg',
`added` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`views` int(255) NOT NULL DEFAULT '0',
`active` int(1) NOT NULL DEFAULT '0',
`owned` int(1) NOT NULL DEFAULT '0',
PRIMARY KEY (`id`),
UNIQUE KEY `arc` (`arc`,`title`,`issue`,`publisher`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
CREATE TABLE IF NOT EXISTS `publishers` (
`id` int(255) NOT NULL AUTO_INCREMENT,
`name` varchar(255) NOT NULL,
`plot` longtext NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `name` (`name`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
答案 0 :(得分:1)
您必须向我们提供有关表格结构的更多信息。
我的第一种方法是这样的......
Select
cs.arc as 'Arc',
arcs.title as 'Arc_Title',
id as 'Issues'
from
Comics cs
left join Arcs arcs on cs.arc = arcs.id
left join Comics cs2 on cs.arc = cs2.arc and publisher = @pid
但我真的不知道,因为我在猜表格结构
修改... 强>
据我所知,一个弧可以出现在多个漫画中。而且你需要不同的弧线以及它们重复的次数。 所以我认为这会奏效:
Select
t1.arc as 'Arc_ID',
t1.title as 'Arc_Title',
count(t1.arc) as 'issues'
from (
Select c.id, c.arc, a.title
from comics c
left join arcs a on c.arc = a.id
where c.publisher = 1) as t1
group by t1.arc, t1.title
这是一个例子.. http://sqlfiddle.com/#!2/a9fda/8/0