I have an SQL query:
DELETE n1
FROM satellites n1
, satellites n2
WHERE n1.id < n2.id
AND n1.norad_cat_id = n2.norad_cat_id
What this query does is delete rows that have the same norad_cat_id and only leave one with the highest id. I don't know if my SQL query is correct, but I will have to see.
I am a bit stuck when it comes to running raw SQL queries in Laravel. From this documentation (https://laravel.com/docs/5.4/database#running-queries) you can see that you have a few options to run the query:
DB::update('SQL QUERY HERE');
DB::delete('SQL QUERY HERE');
DB::statement('SQL QUERY HERE');
DB::select( DB::raw('SQL QUERY HERE'));
In my case I am trying to delete duplicate rows while only leaving the one with the highest id. What Laravel DB statement do I run to achieve the results I want or does it matter at all?
EDIT: SQL query for #MasudMiah
delete satellites
from satellites
inner join (
select max(id) as lastId, norad_cat_id
from satellites
group by norad_cat_id
having count(*) > 1) duplic on duplic.norad_cat_id = satellites.norad_cat_id
where satellites.norad_cat_id < duplic.lastId;
If you want to run directly your DELETE SQL query, you can use:
$nrd = DB::delete('SQL QUERY HERE');
It returns the number of affected /deleted rows.
See this page:
http://coursesweb.net/laravel/working-mysql-database#anc_rsq
I am afraid your query is not right though. but let me show you some :
DELETE FROM table1 WHERE user_id='$your_provided_value';
DELETE FROM table2 WHERE user_id='$your_provided_value';
Now using query builder for laravel :
DB::table('table_name')
->where('id',$your_provided_value)
->delete();
One thing I would like to mention to set multiple conditions like id = 1 AND gender = 'male' you need to something like that
DB::table('table_name')->where('id',1)
->where('gendar','male')
->delete();
Now by eloquent :
User:where('id', 1)->delete();
here User is your model for the users table. Hope you are getting some basics.
by visiting below link you get the idea of using eloquent.
https://scotch.io/tutorials/a-guide-to-using-eloquent-orm-in-laravel
Related
I am trying to make a query with codeigniters Query Builder
$this->db->select('*')
->from('users')
->join('user_to_group', 'users.id=user_to_group.user_id')
->where('user_to_group.group_id !=', $group->id);
Here in above code I'm trying to fetch records of users which are not in provided group. This query is working fine at the stage but sometimes it returns same record multiple times as a user can be part of multiple groups. So to overcome this problem I want to apply distinct to this query.
But I don't find the correct way to do it.
Please help..
You need to add group_by in query.
Write your query as below:-
$this->db->select('*')
->from('users')
->join('user_to_group', 'users.id=user_to_group.user_id')
->where('user_to_group.group_id !=', $group->id)
->group_by('users.id'); // add this line
Note : this query will work in only case if you use "user_to_group" table as multiple relation table mean user and group both tables id you used in this third table name "user_to_group".
Use group by if you need unique record on base of group_id
Try this :
$this->db->select('*')
->from('users')
->join('user_to_group', 'users.id=user_to_group.user_id')
->where('user_to_group.group_id !=', $group->id)
->group_by("user_to_group.group_id");
Because you will get multiple record when user is part of multiple group so you will use this to get groups unique records user vise or you will apply both group_id and user_id in group_by to get it unique from both field.
Is it possible to JOIN a subselect with another table in Laravel 5 Query Builder?
I mean - theoretically - something like this:
$sub = DB::table('A')->select(DB::Raw('id, MAX(date)'))->groupBy('id')->get();
$query = DB::table('B')->join($sub, 'B.id', '=', $sub->id)->get();
In my case, in table A I have duplicated rows. I need the ones with max date per id. Then I need to join the result with table B.
As adviced in comments, a workaround follows.
$idArray= DB::table('A')->select(DB::Raw('id, MAX(date)'))->groupBy('id')->lists('id');
$query = DB::table('B')->whereIn('id', $idArray)->get();
But, again, just a workaround.
I try to use different columns within different tables.
Like I want it to run the query If or Where [table.column]
users.username = 'ExampleUsername' AND users.cardnumber = ''
I don't think I can use NULL instead of '', because its an empty text string?
users.cardnumber = NULL
Anyways, I couldn't come further as this:
INSERT INTO users (cardnumber, hasone)
WHERE users.username = 'ExampleName' AND users.cardnumber = ''
SELECT number, sethasone
FROM cards
WHERE cards.used = '0'
LIMIT 1
I'm a bit of new with SQL, but after I got it right I could put the code into my php script.
-
SOLVED! :
I've used two queries for each column.
update users
set hasone=(select sethasone from cards where used='0' LIMIT 1)
where username='TestUser'
and
update users
set cardnumber=(select number from cards where used='0' LIMIT 1)
where username='TestUser'
then I just deleted the row from cards and I was done.
delete from cards
where used = '1'
LIMIT 1
I gave the user a cardnumber from the table cards and delete that row in cards.
I think you are trying to write a nested query but you didn't know how to write it. If you want to write select query within insert or update query so before doing this Click here to read about sub-query or nested query.
Well, I think that you're trying to re-create a JOIN between 2 table. What you need to do is to add a "card_id" field into the users table. Then to get the user AND the card you can do something like :
SELECT * FROM users u LEFT JOIN cards c ON c.id = u.card_id
If you had data in table 1 that you need to use to return data in table 2 for each row returned in table 1. What is more efficient to use a set of querys in PHP one inbedded in the while loop of the other or an SQL function within a query?
for example:
$qry = mysql_query(SELECT date FROM table1)
while($res = mysql_fetch_array($qry))
{
$qry = mysql_query("SELECT name FROM table2 WHERE date=$res['date']")
}
or to do this as a function that returns the Id from table1 within the query.
A (LEFT / RIGHT) JOIN?
Unless I've misunderstood the question...
I think you're looking for JOIN sql syntax. If you have 2 tables: messages and author and you want to return messages with authors. Then you can write following SQL statement:
SELECT m.body, a.name FROM message m
LEFT JOIN author a ON (a.id=m.author_id)
This will return message body with corresponding author name
Table author:
id - primary key
name - name of the author
Table message:
body - text of the message
author_id - id of the author
UPD1:
This will be faster then looping each message and select an author. Because JOIN allows you to return all data in single query (not N x queries when using for loop).
UPD2:
With your tables the query will look like:
SELECT t1.date, t2.name FROM table1 t1 LEFT JOIN table2 t2 ON (t2.date=t1.date)
It depends on if the data is easier to find during the while loop or in the query itself.
So if the DB has to base the sub-query on the result of each row in the main query, and there are 1000 total rows and 100 results in the main query, it has to check all of the rows 100 times, so that's 100,000 sub-queries it runs.
So think it terms of the number of results of the main query. If your while loop has to query the DB 100 times while the DB can do it much faster and efficiently in one query, that's better. But if you want a subset of answers that you can say 'query only based on the last set of results' the while loop is better.
What is more efficient to use
a set of querys in PHP one inbedded in the while loop of the other
or
an SQL function within a query
Seems you answered your question yourself, didn't you?
Every query you send to the dbms has to be sent over the network, parsed, analyzed then executed. You may want to minimize the number of queries sent to the db.
There may be exceptions, for example if the processing of the data requires operations which the dbms is not capable of.
I have an SQL query like this. When iam executing it though my php file it gives time out error. But when running the same query thoruhg php myadmin it gives results within seconds.
SELECT
cake_apartments.id,
cake_apartments.Headline,
cake_apartments.Description,
cake_apartments.photoset_id,
cake_apartments.Rental_Price,
cake_apartments.Bedrooms,
cake_apartments.Bathrooms
FROM
cake_apartments,cake_neighborhoods
WHERE
(cake_apartments.Rented = 0)
AND
(cake_apartments.status = 'Active')
ORDER BY
cake_neighborhoods.Name DESC
I know that increasing the time out may solve the problem. but i don't want to spend more than 30 sec for this query.
the problem is you haven't specific the relationship between your two tables. it returns quickly in phpmyadmin because phpmyadmin adds a LIMIT clause that allows the mysql server to stop sending rows quickly, never getting near the timeout.
you think the query is just retrieving the rows where the apartments are not rented and are active, but what you're really getting is that numbers of rows * the number of neighborhoods in your database.
rewrite your query like this:
SELECT
cake_apartments.id,
cake_apartments.Headline,
cake_apartments.Description,
cake_apartments.photoset_id,
cake_apartments.Rental_Price,
cake_apartments.Bedrooms,
cake_apartments.Bathrooms
FROM
cake_apartments
JOIN
cake_neighborhoods
ON
cake_neighborhoods.id = cake_apartments.neighborhood_id
WHERE
(cake_apartments.Rented = 0)
AND
(cake_apartments.status = 'Active')
ORDER BY
cake_neighborhoods.Name DESC
note that i only guessed at how the two tables are related in the ON clause, so if i got it wrong you'll have to adjust it.
If you ONLY want rows where a match exists, your SQL needs to include an INNER JOIN. If cake_neighborhoods.cake_apartments_id is the name of your foreign key in the cake_neighborhoods table, I suggest rewriting the query as the following:
SELECT
cake_apartments.id,
cake_apartments.Headline,
cake_apartments.Description,
cake_apartments.photoset_id,
cake_apartments.Rental_Price,
cake_apartments.Bedrooms,
cake_apartments.Bathrooms,
cake_neighborhoods.Name
FROM
cake_apartments,cake_neighborhoods
WHERE
(cake_apartments.Rented = 0)
AND
(cake_apartments.status = 'Active')
AND
cake_neighborhoods.cake_apartments_id = cake_apartments.id
ORDER BY
cake_neighborhoods.Name DESC