I need some help with a query as I don't seem to get my head around it.
First table vacancies:
vac_id
vac_title
vac_location
vac_description
is_deleted
status
Second table vacancies_labels:
vac_id
Label_id
Now I would like to get an output containing all vacancies within a certain location but they also cannot contain the label_id '10' nonetheless of the location.
SELECT `v`.*
FROM `vacancies` AS `v`
LEFT JOIN `vacancies_labels` as `vl` ON `v`.`vacancy_id` = `bl`.`vacancy_id`
WHERE `v`.`vac_location` = 'russia'
AND `v`.`is_deleted` != 1
AND `v`.`status` = 1
AND `vl`.`label_id` NOT IN ('10')
GROUP BY `v`.`vacancy_id`
This results only in the vacancies that have a record in the vacancies_labels table that are not 10. It leaves out however all vacancies that have no records at all in the vacancies_labels table but fit within the location range.
What am I missing here?
Thx!
Using a LEFT JOIN, if the record is not found, then the values will return null. But in your WHERE clause, you have
AND `vl`.`label_id` NOT IN ('10')
as NOT IN doesn't consider nulls you have to do something like...
AND ( `vl`.`label_id` NOT IN ('10') OR `vl`.`label_id` IS NULL)
Related
I want to use mysql to check if a value exists in MySQL Database. If the value exists, I want to do nothing (I don't want to fetch any data). If it does not exist, then I want to set some where conditions.
So this is what I have so far, but its not right. because I still get data fetched, if no where condition is set
SELECT *,
CASE
WHEN ( table_name.record = 'inputrecord')
THEN
//Do nothing because it is found already
ELSE
// since inputrecord does not exist, we will start looking for 'id'
( WHERE table_name.id = '123')
END
FROM table_name
NOTE: In the above example, I have written WHEN ( table_name.record = 'inputrecord') and not WHEN ( table_name.record != 'inputrecord'). This is because I want to only continue the query if the data is not in the table.
Perhaps its better to use the IF function with the EXISTS function, but I am not sure how to do it.
Any help would be great. Right now I get errors
This is not how SQL works.
SQL always returns a collection of rows. It may be empty, sometimes rows may contain NULLs. You have to work out your conditions to filter the collection.
A generic example: say, we have a table of cars with columns (model, color, year), and you would like to find something about the cars in your table:
(* Find all red cars *)
select * from cars where color = 'red'
(* Find all red cars from 1985 *)
select * from cars where color = 'red' and year = 1985
(* Find all colors which exist both in 1990 and 2000 *)
select distinct color from cars A where year=1990 and exists (select 1 from cars B where year=2000 and B.color = A.color)
Please tell exactly what you are trying to achieve
EDIT: this should do it
(* select a record cars = 'Audi' only if cars = 'BMW' is not found in the whole table. otherwise. I do not want to select Audi even if it exists *)
select * from cars where model = 'Audi' and not exists (select 1 from cars where model = 'BMW')
here, IF there are BMWs in your table you'll get 0 rows, otherwise a list of Audis
select *
from table_name
where case when table_name.record <> 'inputrecord'
then table_name.id = '123'
else 1=1
end
you can apply the given condition in your code
when input condition does not match then apply your filter condition.
when input condition match(else case )then retrieve your desired result.
Try This...
SELECT *
CASE
WHEN table_name.record = 'inputrecord' THEN 'Unspecified'
WHEN table_name.id = '123' THEN 'table by id'
END
FROM table_name;
My Problem: Getting query results from 2 db tables with PROPEL2 even when second table has no corresponding entries. If the second has corresponding entries than it is no problem.
I have 3 tables: Entry, Contingent and Favorit.
The schema is as follow:
Entry.id [PK]
Entry.contingent_id [FK]
Entry.expert_id
Contingent.id [PK]
Contingent.name
Favorit.id [PK]
Favorit.contingent_id [FK]
Favorit.expert_id
Favorit.pos
I want to get for a specified expert_id ($id) all entries from Entry with contingent-name and if exists the favorit.pos for this expert and contingent. I get the wanted with:
$result = EntryQuery::create()
->filterByExpertId($id)
->join('Entry.Contingent')
->withColumn('Contingent.name','_contingentName')
->join('Contingent.Favorit')
->where('Favorit.expert_id = ?', $id)
->find();
This works only if there exists such a favorit.pos . In some cases this element doesn’t exists (what is wanted from the system). In these cases I want to get the result too just with favorit.pos as empty, null or 0. But Propel doesn’t return me these records.
With MySQL I have no problem to get the desired result:
SELECT entry.* ,
(SELECT favorit.position
FROM contingent, favorit
WHERE
favorit.expert_id = entry.expert_id
AND entry.contingent_id = contingent.id
AND contingent.id = favorit.contingent_id
)
FROM `entry`
JOIN contingent
ON entry.contingent_id = contingent.id
WHERE
entry.expert_id=1;
Use Join left in code:
->join('Contingent.Favorit','selection conditon','left' )
This left work when empty database when condition is false
in condition like 'id'=$id
I am learning how to work with MySQL, and at the moment I succeed to show data from my table, using:
while($objResult2 = mysqli_fetch_assoc($objQuery_product)) {
Results are shown by using this variable $objResult2["id_product"]; this way i can take from DB any field I want like: $objResult2["name"]; $objResult2["email"]; etc.
But what i do if i have in the table more rows with the same id_product?
I want to write a if statment, which counts if id_product repeats. How to do that? If it is a lot of work, atleast please give me an idea of the right tutorial that I must read. Because i am trying second day to fix this, and searched google but i didnt find what i need, or maybe i coulndt understand it....
This is my query
$sql_product = "SELECT * FROM ps_product AS prod";
$join_product = " LEFT JOIN ps_product_lang AS lang ON lang.id_product = prod.id_product";
$join2_product = " LEFT JOIN ps_stock_available AS stok ON stok.id_product = prod.id_product";
$where_product =" WHERE prod.id_category_default = $idp AND lang.id_lang = 8";
$sql_product = $sql_product.$join_product.$join2_product.$where_product;
$objQuery_product = mysqli_query($objConnect, $sql_product) or die ("Error Query [".$sql_product."]");
You can simple remove the same id_product using DISTINCT keyword in your query. Such as:
SELECT DISTINCT id_product FROM my_table
This will give you results with different ids only.
The second way of doing it is taking the output values inside an array.
In your while loop:
$my_array[] = $objResult2["id_product"];
Then using array_filter remove all the duplicates inside the array.
YOu can also use array_count_values() if you want to count the duplicate values.
Ok here we go. For example you are fetching data with this query.
select id_product, name from PRODUCTS;
Suppose above query gives you 5 records.
id_product name
1 bat
2 hockey
2 hockey
3 shoes
4 gloves
Now you got 2,2 and hockey, hockey. Instead of thinking this way that you have to introduce an if statement to filter repeating records or same name or id_product records.
Rewrite your sql query like this.
select distinct id_product, name from PRODUCTS;
Or if you need count of each then my friend you will write your query something like this...
Graham Ritchie, if Andrei needs count of each repeating record then we will do something like this in our query.
SELECT PRODUCT_ID,
COUNT(PRODUCT_ID) AS Num_Of_Occurrences
FROM PRODUCTS
GROUP BY PRODUCT_ID
HAVING ( COUNT(PRODUCT_ID) > 1 );
SELECT id_product,COUNT(*) AS count
FROM tablename
GROUP BY id_product;
This query will then return you two items in your query
$objResult2["id_product"] //and
$objResult2["count"]
The if statement is then just
if($objResult2["count"] > 1){
//Do whatever you want to do with items with more than 1 occurence.
//for this example we will echo out all of the `product_id` that occur more than once.
echo $objResult2["id_product"] . " occurs more than once in the database<br/>";
}
I have two tables 'accounts_transactions' and 'accounts_bills_transactions'.
I have to left join these two using active record of codeigniter.But the names of key columns used to join are different.So I am not getting the key column from the left table in the output .What query should I write to get the key column from the left table included in the result.
My code is
$this->db->select('*');
$this->db->from('accounts_transactions');
$this->db->join('accounts_bills_transactions', 'accounts_transactions.id = accounts_bills_transactions.transaction_id','left');
$query = $this->db->get();
So, as you see the key columns used to join here are , id from left table and transaction_id from second table.The problem is that I am not getting the id from left table in the result.But I am getting all other columns.I assume the problem is because of difference in column names used to join.ie both the column names are not named 'id' .So how can I get the id from left table included in the result.
You could alias them:
$this->db->select('accounts_transatctions.*, account_transactions.id AS a_id,
accounts_bills_transactions.*,
account_bills_transactions.id AS ab_id');
$this->db->from('accounts_transactions');
$this->db->join('accounts_bills_transactions', 'accounts_transactions.id = accounts_transactions.transaction_id','left');
$query = $this->db->get();
The two IDs will now be available as a_id and ab_id (or whatever alias you choose)
Note: I'm not sure if you can alias in AR without avoiding escaping (haven't been using CI for a while). Should you get any error for that reason, just pass false as second parameter of $this->db->select():
$this->db->select('...', false);
you can try this if you confuse of using $this->where or $this->join
$query = $this->db->query("select ......");
return $query;
You problem is so simple. You can use this query
$query = $this->db
->select('at.*')
->select('abt.id as abt_id');
->from('accounts_transactions at');
->join('accounts_bills_transactions abt', 'at.id = abt.transaction_id','left');
->get()
->result();
When same column are used in join it selects only one. You need to give alise to the other column in second table. The best practice is to use a structure like this
accounts_transatctions
--------------------------
accounts_transatctions_id
other_columns
accounts_bills_transactions
---------------------------
accounts_bills_transactions_id
accounts_transatctions_id
other_columns
HI all,
I am trying to figure out how to put this into words even, but I am wanting to know how to format the output from each table separately in a "multiple table" mysql query. The output from the table1 "wall" is formatted within a while loop, but the content from table2 "actions" is already formatted(as 1 line of text with links) before it is inserted into the table(column action_body), so inside the loop I would only be outputting the action_date and action_body columns from the actions table.
I am probably not using the correct sql method(if Im doing anything right at all, that is) for the results I need, so feel free to correct my novice example, or suggest a new way to approach this.
Query:
$query = "SELECT wall.wall_id, wall.wall_owner_id, wall.wall_user_id,
wall.wall_post_date, wall.wall_post_content, actions.action_id,
actions.action_date, actions.action_user_id, actions.action_title,
actions.action_body FROM wall, actions
ORDER BY wall.wall_post_date, actions.action_date DESC";
$result = mysql_query($query);
while( $rows = mysql_fetch_assoc($result) {
// What to put here
}
Any help is appreciated, thanks, Lea
Update after comments
SELECT w.* FROM (
(SELECT
'w' as type,
wall_id as id,
wall_owner_id as owner_id,
wall_user_id as user_id,
wall_post_date as post_date,
NULL as title,
wall_post_content as content
FROM wall
WHERE wall_owner_id = x # user id of owner
)
UNION
(SELECT
'a' as type,
action_id as id,
action_user_id as owner_id,
NULL as user_id,
action_post_date as post_date,
action_title as title,
action_body as content
FROM actions
WHERE action_user_id = x # user id of owner
)
) w
ORDER BY w.post_date DESC
Because you don't JOIN on a specific field, you're gonna get every row-row combination of the two tables, which is a whole lot more data than you probably want.
You'd be better of by doing 2 queries, one for each table. While looping through the result of each table, you can collect the data you want in one array, with the field you want to sort it by as array key.
Then you sort the array, and loop through it to print it out.