Here is the code:
$f = DB::table("topics")
->join("recommends", "topics.id", "=", "recommends.courseid")
->where("recommends.re_type", "=", $re_type)
->where("recommends.re_location", "=", $re_location)
->orderBy("recommends.weigh", "desc");
$s = DB::table("topics")
->orderBy("topics.create_time", "desc");
$f->union($s)->get();
I got a wrong SQL around key word union:
select * from `topics` inner join `recommends`
on `topics`.`id` = `recommends`.`courseid`
where `recommends`.`re_type` = ?
and `recommends`.`re_location` = ?
order by `recommends`.`weigh` desc
union //here!!!!!
select * from `topics` order by `topics`.`create_time` desc
The error info:
SQLSTATE[HY000]: General error: 1221
Incorrect usage of UNION and ORDER BY (SQL: ...)
(Bindings: array ( 0 => 3, 1 => 7, ))
What is the problem?
MySQL UNIONs expect the same columns in all statements. Because you're joining another table in $f, the columns between the two statements don't match.
See MySql SELECT union for different columns?
In this case, it might be less of a headache to use the PDO object directly.
$pdo = DB::connection()->getPdo();
Found another problem with your query. You should relocate your first order by clause:
->orderBy("recommends.weigh", "desc");
It is producing the order by you before union and MySQL will not accept that.
Related
I'm trying to change mySQL query for a faster data retrieval from the server. I have a table with more than 500,000 records but it takes forever to retrieve the data.
I want to change the query from
SELECT
loanapply.loanapplyId,
loanapply.loanAmount,
loanapply.email,
loanapply.approve,
loanapply.loanDate,
mkopakenya.name,
mkopakenya.idno,
mkopakenya.phoneNo,
mkopakenya.verification
FROM
loanapply
LEFT JOIN mkopakenya ON loanapply.email = mkopakenya.email
WHERE
loanapply.approve = 'ongoing'
AND loanapply.del = 'false'
AND loanapply.archive = 0
AND loanapply.loanDate = '$date'
GROUP BY
loanapply.loanapplyId,
loanapply.loanAmount,
loanapply.email,
loanapply.approve,
loanapply.loanDate,
mkopakenya.name,
mkopakenya.idno,
mkopakenya.phoneNo,
mkopakenya.verification
ORDER BY
loanapplyId DESC
LIMIT
$currentSize,
$limit
to
SELECT
loanapply.loanapplyId,
loanapply.loanAmount,
loanapply.email,
loanapply.approve,
loanapply.loanDate,
mkopakenya.name,
mkopakenya.idno,
mkopakenya.phoneNo,
mkopakenya.verification
FROM
loanapply
LEFT JOIN mkopakenya ON loanapply.email = mkopakenya.email AS data1
INNER JOIN (
SELECT
loanapply.loanapplyId
FROM
loanapply
LIMIT
$currentSize,
$limit
) AS data2 ON data1.loanapplyId = data2.loanapplyId
WHERE
loanapply.approve = 'ongoing'
AND loanapply.del = 'false'
AND loanapply.archive = 0
AND loanapply.loanDate = '$date'
ORDER BY
loanapplyId DESC
for faster data retrieval, The second query only returns blank values
for fast data retrival first you should check for valid indexes
be sure you have a proper composite index on loanapply eg:
create index myidx on loanapply ( loanDate, archive, del, approve, email )
and
table mkopakenya column ( email)
anyway (not for better perfomance but for proper use of SQL) you should not use group by without aggregation function (this behaviour is allowed for mysql version <5.7 but, by default, produce error for version >= 5.7) if you need distinct result use DISTINCT clause
SELECT DISTINCT loanapply.loanapplyId
, loanapply.loanAmount
, loanapply.email
, loanapply.approve
, loanapply.loanDate
, mkopakenya.name
, mkopakenya.idno
, mkopakenya.phoneNo
, mkopakenya.verification
FROM loanapply
LEFT JOIN mkopakenya ON loanapply.email = mkopakenya.email
WHERE loanapply.approve='ongoing'
AND loanapply.del='false'
AND loanapply.archive=0
AND loanapply.loanDate='$date'
ORDER BY loanapplyId DESC LIMIT $currentSize, $limit
I have sql query which should shows all records from table swt_modules, but it shows only first row.
$query1 = mysql_query ("SELECT swt_modules.id, swt_modules.name, swt_exam_regs.name AS exam_regs
FROM `swt_modules`
JOIN `swt_exam_regs`
USING ( `id` )
WHERE swt_exam_regs.id = swt_modules.exam_regulation
ORDER BY swt_modules.name DESC , swt_modules.id DESC
LIMIT " . $limit . "");
while ($fetch1 = mysql_fetch_array ($query1))
{
...
}
I have in this table (swt_modules) 3 rows and in each of them value of field "exam_regulation" is 1. In table swt_exam_regs I have only 1 row with 2 columns - id and name. Swt_modules.id stores id number. Which join I should use to be able to see all records?
I would also suggest using mysqli or pdo instead of the now deprecated mysql.
$query1 = mysql_query ("
SELECT
swt_modules.id,
swt_modules.name,
swt_exam_regs.name AS exam_regs
FROM swt_modules
LEFT JOIN swt_exam_regs on swt_exam_regs.id = swt_modules.exam_regulation
ORDER BY
swt_modules.name DESC,
swt_modules.id DESC
LIMIT $limit");
You need to use LEFT JOIN instead of INNER JOIN. Change your query as below. Notice that, I have removed LIMIT since you are trying to fetch all rows.
SELECT swt_modules.id, swt_modules.name, swt_exam_regs.name AS exam_regs
FROM `swt_modules`
LEFT JOIN `swt_exam_regs`
ON swt_exam_regs.id = swt_modules.exam_regulation
ORDER BY swt_modules.name DESC , swt_modules.id DESC
So I have been lookin for mistake for a while, but still can't find it.
Here is the code -
$this->db->select('*');
$this->db->from('friendRequests');
$this->db->where(array('friendRequests.status' => 1, 'users.status' => 1));
$this->db->or_where(array('friendRequests.senderId' => $this->session->userdata('userId'), 'friendRequests.receiverId' => $this->session->userdata('userId')));
$this->db->join('users', 'users.id = '.$this->session->userdata('userId'));
$query = $this->db->get();
It provides me this error -
Unknown column '1' in 'on clause'
SELECT *
FROM (`friendRequests`)
JOIN `users` ON `users`.`id` = `1`
WHERE `friendRequests`.`status` = 1
AND `users`.`status` = 1
OR `friendRequests`.`senderId` = '1'
OR `friendRequests`.`receiverId` = '1'
If an entry is surrounded in backticks it counts as a column even if it would not be one without the backtics. It thinks that 1 is a column on the JOIN line because of this.
Apparently this is a product of the join method in CI. You can fix it very easily by moving that condition to the WHERE clause. There's no need for it to be in the JOIN clause.
JOIN does not work that way; the syntax is:
JOIN 'tablename' ON 'tablename.field' = 'othertable.field'
If I had to assume you were trying to get a user's friend requests:
JOIN 'users' ON 'users'.'id' = 'friendRequests'.'receiverId'
I have the following DQL query:
$q = Doctrine_Query::create()
->select('id')
->from('Comment')
->where("active='?' AND object_id='?' AND group_name = '?'"
, array(1, 1, 'unit'));
Which produce the sql:
SELECT c.id AS c__id, c.group_name AS c__group_name, c.name AS c__name,
c.email AS c__email
FROM comment c
WHERE (c.active = '?' AND c.object_id = '?' AND c.group_name = '?')
bindings: 1, 1, unit
In database table:
id user_id object_id group_name name active
1 0 1 unit test 1
When I execute de query it returns 0 rows. Why?
If I go in phpmyadmin and I run
SELECT * FROM comment WHERE active=1 AND object_id=1 AND group_name='unit'
the result contains the record I look for.
In phpmyadmin the query generated by Doctrine identify the table name as 'c'. This is very strange, since I used in my application other DQL querys like this one and works.
Thanks.
Remove quotes around parameter placeholders:
where("active=? AND object_id=? AND group_name = ?"
or use named parameters:
where("active= :ative AND object_id= :object_id AND group_name = :group_name"
, array(':ative'=>1, ':objet_id'=>1, 'group_name'=>'unit')"
I want to random show 6 news/reviews on my front page but it shows the same content 6 times random but I will not have duplication of content. Here is the SQL query:
SELECT
anmeldelser.billed_sti ,
anmeldelser.overskrift ,
anmeldelser.indhold ,
anmeldelser.id ,
anmeldelser.godkendt
FROM
anmeldelser
LIMIT 0,6
UNION ALL
SELECT
nyheder.id ,
nyheder.billed_sti ,
nyheder.overskrift ,
nyheder.indhold ,
nyheder.godkendt
FROM nyheder
ORDER BY rand() LIMIT 0,6
showing my example with active record for simplicity,
try randomizing your offset instead of the order, while still limiting to 6
// get the total number of rows
$total_rows = $this->db->count_all_results('my_table');
// offset random point within the total rows
$offset = rand( 0 , $total_rows - 6 );
$q = $this->db->offset( $offset )->limit( 6 )->get( 'my_table' );
print_r( $q->result_array() );
//initialize query builder
$sql1=$sql2=$this->db;
$sql1->select('anmeldelser.billed_sti ,anmeldelser.overskrift ,anmeldelser.indhold ,anmeldelser.id ,anmeldelser.godkendt');
$sql1->from('anmeldelser');
$sql1->order_by('rand()');
$sql1->limit(3);
//get only sql string
$query1=$sql1->get_compiled_select();
$sql2->select('nyheder.id ,nyheder.billed_sti ,nyheder.overskrift ,nyheder.indhold ,nyheder.godkendt');
$sql2->from('nyheder');
$sql2->order_by('rand()');
$sql2->limit(3);
$query2=$sql2->get_compiled_select();
//combine two query
$query = $this->mydb->query("($query1) UNION ($query2)");
$result = $query->result();
I am assuming that you need to join a Two table by this comment of yours.
You didn't mention your foreign key so I am assuming that also.
It is also not clear that the column name of your tables are same or not.
So, I am posting an join query for your table in which I assume your foreign key and column name, so please correct that before using it.
Here is your query to join your table:
$query = $this->db
->select('an.billed_sti,an.overskrift,an.indhold,an.id,an.godkendt, ny.id as ny_id,ny.billed_sti as ny_billed_sti, ny.overskrift as ny_overskrift, ny.indhold as ny_indhold , ny.godkendt as ny_godkendt ')
->from('anmeldelser as an')
->join('nyheder as ny', 'ny.id_fk = an.id', 'left outer') // I am assuming here that the [id_fk] field is the foreign key
->limit(0, 6)
->order_by('puttablename.tablecolumn', 'asc') // Your you table name and column name by which you want to order, you can use [asc/desc] as your need
->get();
And If you want to UNION here is the solution for it.