MYSQL: select where / and / or with two tables - mysql

I am trying to get the following SQl working:
SELECT * FROM tc_appointment as tcAppointment, tc_message as tcMessage
WHERE tcAppointment.counsellor_id = 502
AND
(
(tcAppointment.tc_message_id = tcMessage.id AND tcMessage.marked_read = false AND tcMessage.sender_id != 502)
OR
(tcAppointment.cancelled = true AND tcAppointment.cancelled_acknowledged = false)
OR
(tcAppointment.confirmed = false)
);
The tcAppointment.tc_message_id is null in the only tc_appointment entry in the table. I am trying to get it to return as the counsellor_id = 502 and the second OR statment is true
I seem to be getting stuck because of the tc_message as tcMessage clause and the first AND / OR statement but I'm not sure why. Can anyone point me in the right direction please?

Try Joining the 2 tables and use the 'Where':
SELECT * FROM tc_appointment as tcAppointment
LEFT JOIN tc_message as tcMessage
ON
((tcAppointment.tc_message_id = tcMessage.id AND tcMessage.marked_read = false AND tcMessage.sender_id != 502)
OR
(tcAppointment.cancelled = true AND tcAppointment.cancelled_acknowledged = false)
OR
(tcAppointment.confirmed = false)
)
WHERE tcAppointment.counsellor_id = 502

Related

Having trouble transcribing mySQL query in peewee

I have a query in mySQL that produces desired output when entered into the mySQL terminal, however, I'm having trouble trying to write the same query in the Peewee ORM.
Here is the mySQL query:
select t.PATH, s.PATH from media_data as t
left outer join media_data as s on
s.SHOW = t.SHOW and s.EPISODE = t.EPISODE and s.SHOT = t.SHOT and s.FRAME = t.FRAME and t.LABEL_TYPE = 'target'
where s.LABEL_TYPE = 'source' and s.SHOW = 'doc_d' and s.EPISODE = '102'
union
select t.PATH, s.PATH from media_data as t
right outer join media_data as s on
s.SHOW = t.SHOW and s.EPISODE = t.EPISODE and s.SHOT = t.SHOT and s.FRAME = t.FRAME and t.LABEL_TYPE = 'target'
where s.LABEL_TYPE = 'source' and s.SHOW = 'doc_d' and s.EPISODE = '102';
And here is my attempt at the corresponding peewee query
s = media_data.alias()
t = media_data.alias()
predicate = (s.SHOW == t.SHOW and s.EPISODE == t.EPISODE and s.SHOT == t.SHOT
and s.FRAME == t.FRAME and t.LABEL_TYPE == 'target')
query = media_data.select(s.PATH, t.PATH).join(t, join_type=JOIN.FULL_OUTER, on=predicate).where(s.LABEL_TYPE == 'source' and s.SHOW == show and s.EPISODE == episode)
When I try to run python, it tells me there's a problem with 'JOIN.FULL_OUTER' even though it is used exactly as defined in the syntax.
There are a couple issues. First you need to use & instead of and in your predicates and to use parentheses to properly bind these:
predicate = ((S.show == T.show) &
(S.episode == T.episode) &
(S.shot == T.shot) &
(S.frame == T.frame) &
(T.label_type == 'target'))
Additionally, if your database is complaining about full outer join, perhaps it does not support this type of JOIN (and hence the reason for the awkward UNION query)?
If you have confirmed that your database does support full outer join, then the following should work:
T = MediaData.alias()
predicate = ((MediaData.show == T.show) &
(MediaData.episode == T.episode) &
(MediaData.shot == T.shot) &
(MediaData.frame == T.frame) &
(T.label_type == 'target'))
query = (MediaData
.select(MediaData.path, T.path)
.join(T, join_type=JOIN.FULL_OUTER, on=predicate)
.where(
(MediaData.label_type == 'source') &
(MediaData.show == 'doc_d') &
(MediaData.episode == '102')))
Query:
SELECT "t1"."path", "t2"."path"
FROM "mediadata" AS "t1"
FULL OUTER JOIN "mediadata" AS "t2" ON (
("t2"."show" = "t1"."show") AND
("t2"."episode" = "t1"."episode") AND
("t2"."shot" = "t1"."shot") AND
("t2"."frame" = "t1"."frame") AND
("t2"."label_type" = 'target'))
WHERE (
("t1"."label_type" = 'source') AND
("t1"."show" = 'doc_d')) AND
("t1"."episode" = '102'))

how can I update a mysql record using a form with mutliple inputs but only update the inputs with values entered

so my problem is this, I have a 3 part form that is a service ticket, the 1st part of the form is filled out by the dispatcher and submitted to mysql, the technician then see's they have a ticket assigned to them via email and they pull up the search result for tickets assigned to them and they click on a link in the search result that displays the 2nd form for them to enter what they did and what material and labor there is, this 2nd part of the form is my issue it has multiple values that are similar such as item_qty1, item_qty2, item_qty3 and so on. When I use more than 1 value like item_qty1 in my UPDATE tickets SET query I get a syntax error. Also, I am well aware that my code is subject to sql injection and I will deal with that when I have a working form. So here is my code:
<?php
// database connection //
include 'db_connect.php';
include 'data/var/variables.php';
//Writes the information to the database
mysql_query("UPDATE tickets SET work_performed = $work_performed,
item_qty1 = $item_qty1,
item_qty2 = $item_qty2,
item_qty3 = $item_qty3,
item_qty4 = $item_qty4,
item_qty5 = $item_qty5,
manuf_1 = $manuf_1,
manuf_2 = $manuf_2,
manuf_3 = $manuf_3,
manuf_4 = $manuf_4,
manuf_5 = $manuf_5,
part_number1 = $part_number1,
part_number2 = $part_number2,
part_number3 = $part_number3,
part_number4 = $part_number4,
part_number5 = $part_number5,
part_description1 = $part_description1,
part_description2 = $part_description2,
part_description3 = $part_description3,
part_description4 = $part_description4,
part_description5 = $part_description5,
part_price1 = $part_price1,
part_price2 = $part_price2,
part_price3 = $part_price3,
part_price4 = $part_price4,
part_price5 = $part_price5,
price_extension1 = $price_extension1,
price_extension2 = $price_extension2,
price_extension3 = $price_extension3,
price_extension4 = $price_extension4,
price_extension5 = $price_extension5,
material_total = $material_total,
sales_tax = $sales_tax,
shipping_cost = $shipping_cost,
work_date1 = $work_date1,
work_date2 = $work_date2,
work_date3 = $work_date3,
work_date4 = $work_date4,
work_date5 = $work_date5,
tech_name1 = $tech_name1,
tech_name2 = $tech_name2,
tech_name3 = $tech_name3,
tech_name4 = $tech_name4,
tech_name5 = $tech_name5,
cost_code1 = $cost_code1,
cost_code2 = $cost_code2,
cost_code3 = $cost_code3,
cost_code4 = $cost_code4,
cost_code5 = $cost_code5,
pay_rate1 = $pay_rate1,
pay_rate2 = $pay_rate2,
pay_rate3 = $pay_rate3,
pay_rate4 = $pay_rate4,
pay_rate5 = $pay_rate5,
total_hours1 = $total_hours1,
total_hours2 = $total_hours2,
total_hours3 = $total_hours3,
total_hours4 = $total_hours4,
total_hours5 = $total_hours5,
hours_subtotal1 = $hours_subtotal1,
hours_subtotal2 = $hours_subtotal2,
hours_subtotal3 = $hours_subtotal3,
hours_subtotal4 = $hours_subtotal4,
hours_subtotal5 = $hours_subtotal5,
total_hours = $total_hours,
material_total = $material_total,
labor_cost = $labor_cost,
grand_total = $grand_total WHERE `id` = '$id'");
mysql_affected_rows();
echo mysql_error();
?>
The code as it is wont post to the database, it displays the error:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ' item_qty1 = , item_qty2 = , item_qty3 = ' at line 1
I was told I don't need apostrophe's or back ticks on my values so I removed them and still get the error. Now I changed my code a bit to remove any similar values, example I removed any value beyond value 1 so item_qty2, item_qty3 and so on I removed so I now have this code:
mysql_query("UPDATE `tickets` SET `work_performed` = '$work_performed',
`item_qty1` = '$item_qty1',
`manuf_1` = '$manuf_1',
`part_number1` = '$part_number1',
`part_description1` = '$part_description1',
`part_price1` = '$part_price1',
`price_extension1` = '$price_extension1',
`material_total` = '$material_total',
`sales_tax` = '$sales_tax',
`shipping_cost` = '$shipping_cost',
`work_date1` = '$work_date1',
`tech_name1` = '$tech_name1',
`cost_code1` = '$cost_code1',
`pay_rate1` = '$pay_rate1',
`total_hours1` = '$total_hours1',
`hours_subtotal1` = '$hours_subtotal1',
`total_hours` = '$total_hours',
`material_total` = '$material_total',
`labor_cost` = '$labor_cost',
`grand_total` = '$grand_total' WHERE `id` = '$id'");
This modified code works flawlessly everytime with no syntax errors and posts to the selected record every single time, but, this wont work for me, I need the additional values OR I need a way for the user to add additional fields to the form if they need to which would solve my problem of not having to enter a value in every field unless they have to. Also if anybody has any examples on how to compress this to make it more "functional" not so bulky I guess, that would be appreciated very much. Thanks!
to just optimize the code, what can be done is :
// define an array of column names and values got from input.
$column_names = array('column1' => $column1, 'column2' => $column2, .....);
// built an sql select clause
$select_clause = array();
foreach ($column_names as $cn => $cn_val) {
if (!empty($cn_val)) {
$select_clause = "{$cn} = {$cn_val}";
}
}
// built proper query
$sql = "UPDATE table_name SET" . implode(',', $select_clause) . " table_name WHERE .....";
// continue with your stuff.

How toPerform a left join in linq pad -

How can I get linq pad to run my left join as show below?
var query =
from s in db.CDBLogsHeaders
.OrderByDescending(g => g.LogDateTime)
from sc in db.StyleColors
.Where(stylecolor => stylecolor.id == (int?)s.StyleColorID)
.DefaultIfEmpty()
from c in db.StyleHeaders
.Where(styleHeader => styleHeader.id == (int?)s.StyleHeaderID)
.DefaultIfEmpty()
select new
{
CDBLogsHeaderId = s.Id,
Merchandiser = c.Merchandiser,
Material = s.Material,
Season = s.Season,
LogsHeaderLogType = s.LogType,
PushFromTo = s.PushFromTo,
LinePlan = s.LinePlan,
QuikRefNumber = s.QuikRefNumber,
PLMOrigin = s.PLM_Origin,
SeasonOriginal = c.SeasonOriginal,
SeasonCurrent = c.SeasonCurrent,
StyleHeaderId = c.Id,
StyleCode = c.StyleCode,
StyleColorsColorCode = sc.ColorCode
};
query.Dump();
The sql that linq pad creates runs perfectly in Management Studio but linq-pad doesn't display any rows and gives this error
InvalidOperationException: The null value cannot be assigned to a
member with type System.Int32 which is a non-nullable value type.
How can I get linqpad to work so I can play with it?
In your anonymous type, make sure your ints are returning ints.
Change
StyleHeaderId = c.Id,
To
StyleHeaderId = (c.Id == null ? 0 : c.Id),

"ERROR: Only one expression can be specified in the select list" Linq To Sql

var loggedInHours = db.LoginLogs.Where(l => l.UserId == u.Id && l.UserSessionStop != null)
.Sum(ls=> ls.UserSessionStart.Subtract(ls.UserSessionStop.Value).Hours)
I am trying to calculate Total LoggedIn Hours using this linq query..
But its giving me this error
"Only one expression can be specified in the select list when the subquery is not introduced with EXISTS."
I don't know whats wrong with it..plz help
Try if this works:
var loggedInHours = db.LoginLogs.Where(l => l.UserId == u.Id && l.UserSessionStop != null)
.Select(l=> new {
StartTime = l.UserSessionStart,
EndTime = l.UserSessionStop
})
.ToList()
.Sum(c=> c.StartTime - c.EndTime);
btw, Is UserSessionStop nullable? If yes, then what will be the value to be subtracted?

Help to build LINQ query

I have SQL database as follows
alt text http://img97.imageshack.us/img97/5774/dbimage.jpg
Now I want to filter the restaurant_detail table for the parameters:
1. cuisine 2. area
Can you help me to build LINQ query?
I presume you have a model generated either with LINQ to SQL or Entity Framework. Also, I'm assuming foreign key relationships have been set.
var details = db
.Cuisines
.Where(c => c.Cuisine=="something")
.SelectMany(c => c.RestaurantCuisines)
.Select(rc => rc.Restaurant.RestaurantDetails)
.Where(rd => rd.Area=="something")
;
Done with the linq query using following lines of code :
c = from q in dc.restaurant_cuisines
where q.cuisine.cuisine1.Contains(cuisine)
&& q.restaurant.price.ToString().Length == price.Length
select new NearBy { NearById = q.restaurant.id, NearByLongitude = (double)q.restaurant.longitude, NearByLatitude = (double)q.restaurant.latitude };
}
int[] ids = new int[c.Count()];
var lon = from q1 in dc.area_maps where q1.area.ToLower() == area.ToLower() select q1.longtitude;
var lat = from q1 in dc.area_maps where q1.area.ToLower() == area.ToLower() select q1.latitude;
foreach(NearBy n in c)
{
result = calcDistNew((double)lat.FirstOrDefault(), (double)lon.FirstOrDefault(), n.NearByLatitude, n.NearByLongitude);
ids[i++] = n.NearById;
}
var r = from q in dc.restaurant_details
where 1 == 1 &&
(ids).Contains(q.restaurant_id)
select new Restaurant
{
Restora_id = q.restaurant_id.ToString(),
Name = q.restaurant.name,
Foodtype = q.restaurant.foodtype.foodtype1,
Avg_rating = q.restaurant.avg_rating.ToString(),
Featured = q.restaurant.featured.ToString(),
CuisineList = getCuisine(q.restaurant_id),
Restora_type = q.type,
Distance = Math.Round(calcDistNew((double)lat.FirstOrDefault(), (double)lon.FirstOrDefault(), (double)q.restaurant.latitude, (double)q.restaurant.longitude), 2),
Newarrival = q.restaurant.newarrival.ToString(),
CountRecord = ids.Length.ToString()
};
var d = r.AsEnumerable().OrderBy(t => t.Distance);
var g = d.Take(recordSize + 10).Skip(recordSize);
return g.ToList();
Please note that above displayed code generated with some changes from the initial requirements.