Php union all select

PHP Zend Framework — How do I use union all?

You need to pass an array of Zend_Db_Select into the union() method. The second parameter to be passed to the union() method to perform the type of UNION. In your case, use Zend_Db_Select::SQL_UNION_ALL as a constant.

$sql1 = $db->select(); $sql2 = "SELECT . "; $select = $db->select() ->union(array($sql1, $sql2), Zend_Db_Select::SQL_UNION_ALL ); 

union( array $select = array, $type = self ) : Zend_Db_Select

Adds a UNION clause to the query.

The first parameter has to be an array of Zend_Db_Select or sql query strings.

$sql1 = $db->select(); $sql2 = "SELECT . "; $select = $db->select() ->union(array($sql1, $sql2)) ->order("id"); 

The same example and some additional text can be found in the Example #28 Example of union() method in the ZF Reference guide. Apart from that, you can always use Zend_Db_Expr when you dont need the Query Builder.

$select = union($select1, $select2, self::SQL_UNION_ALL). 
$select1 = 'select A from table1'; $select2 = 'select A from table2'; $select = $db->select()->union($select1, $select2, Zend_Db_Select::SQL_UNION_ALL); echo $select; 

Result: (SELECT A FROM TABLE1) UNION ALL (SELECT A FROM TABLE2).

here is the running example

select CONCAT_WS(' ', u.fname, u.lname) as user_name, u.image, c.* from challenge c inner join challenge_user cu on (cu.challenge_id = c.id) inner join users u on (u.id = c.user_id) where c.user_id = '1' group by c.id union all select CONCAT_WS(' ', u.fname, u.lname) as user_name, u.image, c.* from challenge c inner join challenge_user cu on (cu.challenge_id = c.id) inner join users u on (u.id = c.user_id) where concat('%,',c.challenger_user_id,',%') LIKE concat( '%,"1",%' ) group by c.id 
 $sql1 = $this->select()->setIntegrityCheck(FALSE) ->from(array('c'=>'challenge'),array('user_name'=>new Zend_Db_Expr("CONCAT_WS(' ', u.fname, u.lname)"),'u.image')) ->joinInner(array('cu'=>'challenge_user'), 'cu.challenge_id = c.id') ->joinInner(array('u'=>'users'),'u.id = c.user_id') ->where('c.user_id = ?','1') ->group('c.id'); $sql2 = $this->select()->setIntegrityCheck(FALSE)->from(array('c'=>'challenge'),array('user_name'=>new Zend_Db_Expr("CONCAT_WS(' ', u.fname, u.lname)"),'u.image')) ->joinInner(array('cu'=>'challenge_user'), 'cu.challenge_id = c.id') ->joinInner(array('u'=>'users'),'u.id = c.user_id') ->where(new Zend_Db_Expr("concat('%,',c.challenger_user_id,',%') LIKE concat( '%,"1",%' )"))->group('c.id'); $select = $this->select()->union(array($sql1,$sql2), Zend_Db_Select::SQL_UNION_ALL); $data = $this->fetchAll($select); 

Hope it will help some one

Источник

Php union all select

Оператор UNION позволяет обединить две однотипных выборки. Эти выборки могут быть из разных таблиц или из одной и той же таблицы. Формальный синтаксис объединения:

SELECT_выражение1 UNION [ALL] SELECT_выражение2 [UNION [ALL] SELECT_выражениеN]

Например, пусть в базе данных будут две отдельные таблицы для клиентов банка (таблица Customers) и для сотрудников банка (таблица Employees):

CREATE TABLE Customers ( Id INT AUTO_INCREMENT PRIMARY KEY, FirstName VARCHAR(20) NOT NULL, LastName VARCHAR(20) NOT NULL, AccountSum DECIMAL ); CREATE TABLE Employees ( Id INT AUTO_INCREMENT PRIMARY KEY, FirstName VARCHAR(20) NOT NULL, LastName VARCHAR(20) NOT NULL ); INSERT INTO Customers(FirstName, LastName, AccountSum) VALUES ('Tom', 'Smith', 2000), ('Sam', 'Brown', 3000), ('Mark', 'Adams', 2500), ('Paul', 'Ins', 4200), ('John', 'Smith', 2800), ('Tim', 'Cook', 2800); INSERT INTO Employees(FirstName, LastName) VALUES ('Homer', 'Simpson'), ('Tom', 'Smith'), ('Mark', 'Adams'), ('Nick', 'Svensson');

Здесь мы можем заметить, что обе таблицы, несмотря на наличие различных данных, могут характеризоваться двумя общими атрибутами — именем (FirstName) и фамилией (LastName). Выберем сразу всех клиентов банка и его сотрудников из обеих таблиц:

SELECT FirstName, LastName FROM Customers UNION SELECT FirstName, LastName FROM Employees;

Здесь из первой таблицы выбираются два значения — имя и фамилия клиента. Из второй таблицы Employees также выбираются два значения — имя и фамилия сотрудников. То есть при объединении количество выбираемых столбцов и их тип совпадают для обеих выборок.

Читайте также:  Php sort by number

UNION в MySQL

При этом названия столбцов объединенной выборки будут совпадать с названия столбцов первой выборки. И если мы захотим при этом еще произвести сортировку, то в выражениях ORDER BY необходимо ориентироваться именно на названия столбцов первой выборки:

SELECT FirstName AS FName, LastName FROM Customers UNION SELECT FirstName, LastName FROM Employees ORDER BY FName DESC;

В данном случае каждая выборка имеет по столбцу FName из первой выборки. Тем не менее при сортировке будет учитываться и значение столбца FirstName из второй выборки:

Сортировка в UNION в MySQL

Если же в одной выборке больше столбцов, чем в другой, то они не смогут быть объединены. Например, в следующем случае объединение завершится с ошибкой:

SELECT FirstName, LastName, AccountSum FROM Customers UNION SELECT FirstName, LastName FROM Employees;

Если оба объединяемых набора содержат в строках идентичные значения, то при объединении повторяющиеся строки удаляются. Например, в случае с таблицами Customers и Employees сотрудники банка могут быть одновременно его клиентами и содержаться в обеих таблицах. При объединении в примерах выше всех дублирующиеся строки удалялись. Если же необходимо при объединении сохранить все, в том числе повторяющиеся строки, то для этого необходимо использовать оператор ALL :

SELECT FirstName, LastName FROM Customers UNION ALL SELECT FirstName, LastName FROM Employees ORDER BY FirstName;

Обединение повторяющихся строк в MySQL

Объединять выборки можно и из одной и той же таблицы. Например, в зависимости от суммы на счете клиента нам надо начислять ему определенные проценты:

SELECT FirstName, LastName, AccountSum + AccountSum * 0.1 AS TotalSum FROM Customers WHERE AccountSum < 3000 UNION SELECT FirstName, LastName, AccountSum + AccountSum * 0.3 AS TotalSum FROM Customers WHERE AccountSum >= 3000;

В данном случае если сумма меньше 3000, то начисляются проценты в размере 10% от суммы на счете. Если на счете больше 3000, то проценты увеличиваются до 30%.

Читайте также:  Стим аккаунт для css

Источник

How can I union 2 tables in PHP & MySQL?

Line 19 is while’s line. How can I fix it? I want to union 2 table, order by date all limit 10. EDIT: news table:

id | site_id | title | date (timestamp) 
id | title | date (timestamp) 

EDIT: The problem was solved. I learned, if we want to use union or union all, our tables have to have same column number.

edit your question to show us what the schema is for the tables. Also check for errors on the query, you will see what’s going on or not.

1 Answer 1

To union these 2 tables you will have to add an extra dummy column to the Query of the shorter table so the rules of UNION are met.

You dont need to add a real column to the schema for that table!

id | site_id | title | date (timestamp) 
id | title | date (timestamp) 

Then the query can be written like this

SELECT id, site_id, title, date FROM news WHERE site_id = '1' UNION ALL SELECT id, 0, title, date FROM all_news 

Note I added a dummy column to the select list of the all_news table so that the column count and the datatypes of each column match each other.

You can use any number you like other than 0 , so pick one that identifies this as data you dont want to process, or it can be used to identify the rows from all_news by setting a specific value.

Note: I assumed site_id was an integer, if its a text then use ‘0’ for example or ‘IGNORE ME’ .

Источник

How to UNION ALL two SELECT statements?

I want to combine a Select statement that grabs data from both tables and output the results. The following code:

$select = mysql_query(" SELECT * FROM table_one WHERE Username = 'Bob' UNION ALL SELECT * FROM table_two WHERE Hobby = 'Baseball' "); while ($return = mysql_fetch_assoc($select)) < $userName = $return['Username']; $hobby = $return['Hobby']; >echo "$userName likes $hobby"; 

results in a The used SELECT statements have a different number of columns error, what am I doing wrong? EDIT: Running this gives the following error: Warning: mysql_fetch_assoc(): supplied argument is not a valid MySQL result resource in /home/studentw/public_html/foo.php on line 16

$select = mysql_query(" SELECT FROM TABLE_ONE t1 INNER JOIN TABLE_TWO t2 ON t1.id = t2.id WHERE t1.Username = 'Bob' AND t2.Hobby = 'Baseball' "); while ($return = mysql_fetch_assoc($select)) < $firstName = $return['Username']; $hobby = $return['Hobby']; >echo "$firstName likes $hobby"; 
id | Last Name | First Name | Username | Password | Secret Question 1 | Hughes | Bobby | Bob | 123 | Maiden name? 
id | Hobby | Country | 1 | Baseball | USA 

2 Answers 2

I think you want a JOIN, not a UNION or UNION ALL.

SELECT FROM TABLE_ONE t1 INNER JOIN TABLE_TWO t2 ON t1.id = t2.id WHERE t1.Username = 'Bob' AND t2.Hobby = 'Baseball' 

Unions require that the data columns of each table be the same number and type, and basically give you a concatenation of multiple rows from different tables. Joins, on the other hand, essentially expand one table into a wider one with more columns by literally joining another table’s columns to it.

Читайте также:  Метод integer parseint java

When you do a join, you need to specify how the rows of one table correspond to the other; in this case, I’m assuming that your Id field is supposed to be a primary/foreign key linking the tables together. Apologies if that is incorrect— if that is so, I will need more information in order to properly help you.

I’ll first link you to the documentation for the mysql_query function. It has one required and one optional argument; the second argument is your connection handle. If you don’t specify it, then PHP assumes that the last connection opened with mysql_connect is the one you want to use. So my first question is, did you call mysql_connect properly and did that call work successfully?

If you’re sure the mysql_connect call worked, then I’m not sure what the problem could be. I don’t think it could hurt, though, to assign the result of mysql_connect to a variable so you can explicitly specify the connection in mysql_query . Maybe something like the following:

$conn = mysql_connect("localhost:3306", "username", "password"); $query = "select * from some_table"; // obviously use your own query here $result = mysql_query($query, $conn); 

Let me know if that doesn’t work.

Источник

Оцените статью